/**
 * SQLite 数据库服务
 */
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import * as sqlite3 from 'sqlite3';
import * as path from 'path';
import { promisify } from 'util';

@Injectable()
export class DatabaseService implements OnModuleInit, OnModuleDestroy {
  private db: sqlite3.Database;
  private readonly dbPath: string;

  constructor() {
    this.dbPath = path.join(process.cwd(), 'bazi_data.db');
  }

  async onModuleInit() {
    await this.connect();
  }

  async onModuleDestroy() {
    await this.close();
  }

  /**
   * 连接数据库
   */
  private connect(): Promise<void> {
    return new Promise((resolve, reject) => {
      this.db = new sqlite3.Database(this.dbPath, (err) => {
        if (err) {
          console.error('❌ 数据库连接失败:', err.message);
          reject(err);
          return;
        }
        console.log(`✅ 数据库连接成功: ${this.dbPath}`);
        resolve();
      });
    });
  }

  /**
   * 关闭数据库连接
   */
  private close(): Promise<void> {
    return new Promise((resolve, reject) => {
      if (!this.db) {
        resolve();
        return;
      }
      this.db.close((err) => {
        if (err) {
          console.error('❌ 关闭数据库失败:', err.message);
          reject(err);
          return;
        }
        console.log('✅ 数据库连接已关闭');
        resolve();
      });
    });
  }

  /**
   * 执行查询（返回单条记录）
   */
  async get<T = any>(sql: string, params: any[] = []): Promise<T | undefined> {
    return new Promise((resolve, reject) => {
      this.db.get(sql, params, (err, row) => {
        if (err) {
          reject(err);
          return;
        }
        resolve(row as T);
      });
    });
  }

  /**
   * 执行查询（返回多条记录）
   */
  async all<T = any>(sql: string, params: any[] = []): Promise<T[]> {
    return new Promise((resolve, reject) => {
      this.db.all(sql, params, (err, rows) => {
        if (err) {
          reject(err);
          return;
        }
        resolve(rows as T[]);
      });
    });
  }

  /**
   * 执行更新操作（INSERT, UPDATE, DELETE）
   */
  async run(sql: string, params: any[] = []): Promise<sqlite3.RunResult> {
    return new Promise((resolve, reject) => {
      this.db.run(sql, params, function (err) {
        if (err) {
          reject(err);
          return;
        }
        resolve(this);
      });
    });
  }

  /**
   * 获取数据库实例（用于复杂操作）
   */
  getDatabase(): sqlite3.Database {
    return this.db;
  }
}

